using System.Threading.Tasks;
using Gj.Galaxy.Logic;
using SimpleJSON;

namespace Gj.LeanCloud
{
    public class Auth
    {
        public static string SessionToken = "";
        public static string ObjectId = "";

        public static bool IsLogin()
        {
            return !string.IsNullOrEmpty(SessionToken);
        }

        public static async Task Login(GamePlayer player)
        {
            if (!IsLogin())
            {
                var data = new JSONObject();
                data["authData"] = new JSONObject();
                var platform = new JSONObject();
                var instance = player.Instance;

                // if (instance["platform"] == "local")
                // {
                //     platform["openid"] = "extendid";
                // }
                // else
                // {
                //     platform["openid"] = instance["openId"];
                //     if (instance["unionId"])
                //     {
                //         platform["unionid"] = instance["unionId"];
                //     }
                // }
                
                platform["openid"] = instance["openId"];
                if (instance["unionId"])
                {
                    platform["unionid"] = instance["unionId"];
                }

                // platform["main_account"] = true;
                data["authData"][instance["platform"].Value] = platform;
                var result = await Api.Post("/users", data, Api.BaseHeader());
                SessionToken = result["sessionToken"];
                ObjectId = result["objectId"];
                if (result["response"] != "OK")
                {
                    var updateData = new JSONObject();
                    var nickname = new JSONObject();
                    nickname["name"] = instance["nickName"] ? instance["nickName"] : "local";
                    updateData["nickName"] = nickname;
                    await Update(updateData);
                }
            }
            // var info = await Self();
            // if (info["nickName"] != player.Instance["nickName"])
            // {
            //     var updateData = new JSONObject();
            //     updateData["nickName"] = player.Instance["nickName"];
            //     await Update(updateData);
            // }
        }

        public static async Task<JSONObject> Self()
        {
            var header = Api.BaseHeader();
            header["X-LC-Session"] = Auth.SessionToken;
            var info = await Api.Get("/users/me", null, header);
            return info.AsObject;
        }

        public static async Task Update(JSONObject data)
        {
            var header = Api.BaseHeader();
            header["X-LC-Session"] = Auth.SessionToken;
            await Api.Put($"/users/{ObjectId}", data, header);
        }
    }
}